package com.vastcom.sse.action;

import com.vastcom.sse.to.SseParm;
import com.vastcom.sse.tools.SseEmitterTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;

@CrossOrigin
@RestController
@RequestMapping("/public")
public class PublicAction {


    private Logger log= LoggerFactory.getLogger(PublicAction.class);



    @GetMapping("connect2SSE")
    @ResponseBody
    public SseEmitter connect2SSe(@RequestParam ("userid") String userid) throws Exception{

        SseEmitter sseEmitter= SseEmitterTools.connect(userid);
        SseEmitterTools.sendMessage(userid,"connected");

        return sseEmitter;

    }


    @PostMapping("sendSSEMessageToUser")
    @ResponseBody
    public HashMap sendSSEMessageToUser(@RequestBody SseParm parm) throws Exception{

        HashMap m=new HashMap();


        try {
            SseEmitterTools.sendMessage(parm.getUserid(),parm.getMessage());
            m.put("msg","ok");
        } catch (Exception e) {
            e.printStackTrace();
            m.put("nsg","error");
        }


        return m;
    }


   @PostMapping("sendSSEMessageToAllUsers")
    @ResponseBody
    public  HashMap sendSSEMesageToAllUser(@RequestBody SseParm parm) throws Exception{

        HashMap m=new HashMap();

       try {
           SseEmitterTools.batchSendMessage(parm.getMessage());
           m.put("msg","ok");
       } catch (Exception e) {
           e.printStackTrace();
           m.put("msg","error");
       }

        return m;
   }


   @PostMapping("sendSSEMessageByUserGroup")
    @ResponseBody
    public HashMap sendSSEMessageByUserGroup(@RequestBody SseParm parm) throws Exception{

        HashMap m=new HashMap();


       try {
           SseEmitterTools.batchSendMessage(parm.getUsergroup(), parm.getMessage());
           m.put("msg","ok");
       } catch (Exception e) {
           e.printStackTrace();
           m.put("msg","error");
       }


       return m;
   }


   @PostMapping("closeUserSSEConnect")
    @ResponseBody
    public HashMap closeUserSSEConnect(@RequestBody SseParm parm) throws Exception{


        HashMap m=new HashMap();


       try {
           SseEmitterTools.removeUser(parm.getUserid());
           m.put("msg","ok");
       } catch (Exception e) {
           e.printStackTrace();
           m.put("msg","error");
       }

        return m;
   }






}
